import argparse
import base64
import os

import pandas as pd
from Crypto.Cipher import ARC4
from Crypto.Hash import SHA256
from win32api import GetComputerName, GetUserName
from win32security import LookupAccountName, ConvertSidToStringSid


def encrypt_string(_password):
    """

    :param _password:
    :return:
    """
    _sid = GetUserName() + ConvertSidToStringSid(LookupAccountName(GetComputerName(), GetUserName())[0])
    pwd = str.encode(_password)
    s = ARC4.new(SHA256.new(_sid.encode('ascii')).digest()).encrypt(pwd) + SHA256.new(pwd).digest()
    return base64.b64encode(s).decode()


def read(d, excel):
    """

    :param d:
    :param excel:
    """
    df = pd.read_excel(excel, converters={'password': str})
    arrays = df.values

    with open("default", "r", encoding='utf-8') as f:
        config_template = f.read()
    try:
        for td in arrays:
            p = d + "/" + td[0]

            if not os.path.exists(p):
                os.mkdir(p)

            fp = open(p + "/" + td[1] + ".xsh", 'a+')
            pwd = encrypt_string(td[5])
            fp.write(config_template.format(host=td[2], port=td[3], username=td[4], password=pwd))
            print(td[1] + ".xsh" + "创建成功！")
            fp.close()
    except Exception as e:
        print(e)


parser = argparse.ArgumentParser(description="xsh 批量创建")
parser.add_argument("-f", "--file", default="", type=str, help="输入文件名")
parser.add_argument("-p", "--path", default="", type=str, help="输出路径")
args = parser.parse_args()

if not args.path:
    args.path = os.path.join(os.environ["USERPROFILE"], r"Documents\NetSarang Computer\6\Xshell\Sessions")

if args.file:
    read(args.path, args.file)
